#!/usr/bin/python
#
#   pytunescharts.py
#
#   Copyright Jonathan Carroll (jonathan.carroll@gmail.com)
#   Created On March 8, 2010
#
#   Version 1.0.1 - Initial release
#
#   Project website: http://code.google.com/p/pytunesconnect/
#
#   This script is designed to generate interactive html/java charts through
#   the Google charts API as part of the pyTunesConnect project. The interfaces
#   to build the charts could easily be used for other purposes so I seperated
#   them from the rest of the project. Feel free to use this in your own
#   projects if you like it, if you add additional chart types feel free to
#   send your changes to jonathan.carroll@gmail.com and I will include them in
#   the next public release.
#   
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

def getDygraph(data, divname, width, height): #generates a dygraph (part of the Google Chart Tools library) http://danvk.org/dygraphs/
    """ Called to generate an interactive dygraph (http://danvk.org/dygraphs/)

        Parameters:\n
        data - A list of lists containing the information to be graphed - example: [["Date", "Reinstalls"],["2010-02-22", "200"],["2010-02-23", "150"]]\n
        divname - A string that the div the chart is in will be named.  If you are displaying multiple dygraphs on a page they must have unique div names.\n
        width - A string, the width in pixels of the chart generated\n
        height - A string, the height of the chart generated in pixels

        Returns (touple, two strings):\n
        head - HTML to be placed in the <head> tag of the page where the chart is displated\n
        body - HTML DIV tag to be placed in the body wherever the chart should appear.\n
    """
    head = '<script type="text/javascript" src="http://danvk.org/dygraphs/dygraph-combined.js"></script>'
    body = '<div id="' + divname + '" style="width:' + str(width) + 'px; height:' + str(height) + 'px;"></div>'
    body = body + '<script type="text/javascript"> g2 = new Dygraph(document.getElementById("' + divname + '"),\n'
    csv = ''
    COMMA = ','
    for line in data:
        line[0] = line[0].replace("-","")
        linestr = COMMA.join(line)
        if(data.index(line)==len(data)-1):
            csv = csv + '"' + linestr + '\\n"\n'
        else:
            csv = csv + '"' + linestr + '\\n" +\n'
    body = body + csv
    body = body + ');</script>'
    return head, body

def getGoogleTable(data, divname, columntypes): #generates the interactive javascript Table that is part of the Google Chart Tools Library http://code.google.com/apis/visualization/documentation/gallery/table.html
    """ Called to generate an interactive javascript table (http://code.google.com/apis/visualization/documentation/gallery/table.html)

        Parameters:\n
        data - A list of lists containing the information to be graphed - example: [["Date","Revenue","Units Sold","Currency"],["2010-02-22", "20.70", "20","USD"],["2010-02-22", "15.30", "30","EUR"]]\n
        divname - A string that the div the chart is in will be named.  If you are displaying multiple dygraphs on a page they must have unique div names.\n
        columntypes - A list of strings describing the data types of the columns in data.  Example: ["string", "number", "number", "string"]

        Returns (touple, two strings):\n
        head - HTML to be placed in the <head> tag of the page where the chart is displated\n
        body - HTML DIV tag to be placed in the body wherever the chart should appear.\n
    """
    head = "<script type='text/javascript' src='http://www.google.com/jsapi'></script><script type='text/javascript'>\ngoogle.load('visualization', '1', {packages:['table']});"
    head = head + '\ngoogle.setOnLoadCallback(drawTable);'
    head = head + '\nfunction drawTable() {'
    head = head + '\nvar data = new google.visualization.DataTable();'
    i = 0
    for line in data:
        if(i==0):
            j = 0
            for header in line:
                head = head + "\ndata.addColumn('" + columntypes[j] + "', '" + header + "');"
                j = j + 1
            head = head + "\ndata.addRows(" + str(len(data)-1) + ");"
        else:
            j = 0
            for cell in line:
                ctype = columntypes[j]
                if(ctype=="string"):
                    head = head + "\ndata.setCell(" + str(i-1) + ", " + str(j) + ", '" + str(cell) + "');"
                elif(ctype=="number"):
                    head = head + "\ndata.setCell(" + str(i-1) + ", " + str(j) + ", " + str(cell) + ", '" + str(cell) + "');"
                j = j + 1
        i = i + 1
    head = head + "\nvar table = new google.visualization.Table(document.getElementById('" + str(divname) + "'));"
    head = head + "\ntable.draw(data, {showRowNumber: true});"
    head = head + "\n}"
    head = head + "</script>"
    body = "<div id='" + str(divname) + "'></div>"
    return head, body
def getGoogleIntensityMap(data, divname, columntypes): #generates an intensity map that is part of the Google Chart Tools Library http://code.google.com/apis/visualization/documentation/gallery/intensitymap.html
    """ Called to generate an intensity map (http://code.google.com/apis/visualization/documentation/gallery/intensitymap.html)

        Parameters:\n
        data - A list of lists containing the information to be graphed - example: [["Country", "Units"],["US", "200"],["UK", "150"]]\n
        divname - A string that the div the chart is in will be named.  If you are displaying multiple dygraphs on a page they must have unique div names.\n
        columntypes - A list of strings describing the data types of the columns in data.  Example: ["string", "number"]

        Returns (touple, two strings):\n
        head - HTML to be placed in the <head> tag of the page where the chart is displated\n
        body - HTML DIV tag to be placed in the body wherever the chart should appear.\n
    """
    head = "<script type='text/javascript' src='http://www.google.com/jsapi'></script><script type='text/javascript'>"
    head = head + "\ngoogle.load('visualization', '1', {packages:['intensitymap']});"
    head = head + "\ngoogle.setOnLoadCallback(drawChart);"
    head = head + "\nfunction drawChart() {"
    head = head + "\nvar data = new google.visualization.DataTable();"
    i = 0
    for line in data:
        if(i==0):
            j = 0
            for header in line:
                if(j==0):
                    head = head + "\ndata.addColumn('" + columntypes[j] + "', '', '" + header + "');"
                else:
                    head = head + "\ndata.addColumn('" + columntypes[j] + "', '" + header + "', 'a');"
                j = j + 1
            head = head + "\ndata.addRows(" + str(len(data)-1) + ");"
        else:
            j = 0
            for cell in line:
                ctype = columntypes[j]
                if(ctype=="string"):
                    head = head + "\ndata.setValue(" + str(i-1) + ", " + str(j) + ", '" + str(cell) + "');"
                elif(ctype=="number"):
                    head = head + "\ndata.setValue(" + str(i-1) + ", " + str(j) + ", " + str(cell) + ");"
                j = j + 1
        i = i + 1
    head = head + "\nvar chart = new google.visualization.IntensityMap(document.getElementById('" + str(divname) + "'));"
    head = head + "\nchart.draw(data, {});"
    head = head + "\n}"
    head = head + "</script>"
    body = "<div id='" + str(divname) + "'></div>"
    return head, body


    


